/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { QuestionCircleOutlined } from '@ant-design/icons';
import { message, Popover } from 'antd';
import { DrawerForm, ProFormInstance, ProFormRadio } from '@ant-design/pro-form';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import { useSelector } from 'umi';
import React, { useRef, useState, useEffect } from 'react';
import KbAddressSelect from './KbAddressSelect';
import { addQjLeague, editQjLeague } from '@/services/qj/ChargeCheck';
import AgencyArea from './AgencyArea';

interface AreamanageDrawerType {
  record?: any;
  update: () => void;
}

const AreamanageDrawer: React.FC<AreamanageDrawerType> = (props) => {
  const { children, update, record = {} } = props;
  const { league_id = '' } = record;
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [areaAddress, setAreaAddress] = useState<any>([]);

  const { winSize } = useSelector((state: ConnectState) => state.global);
  const isMobile = winSize === 'xs';

  const formatCompanyAddress = (addressCity: string | string[]) => {
    const { province, city, district } = record;
    const isChange = typeof addressCity == 'string';
    const companyAddress = isChange
      ? {
          province,
          city,
          district,
        }
      : {
          province: areaAddress[0]?.label,
          city: areaAddress[1]?.label,
          district: areaAddress[2]?.label,
        };

    return companyAddress;
  };

  const onFinish = async (values: any) => {
    const { area, league_area, ...rest } = values;
    let api = addQjLeague;
    const params = {
      ...rest,
      league_area: JSON.stringify(league_area),
      ...formatCompanyAddress(area),
    };

    if (league_id) {
      params.league_id = league_id;
      api = editQjLeague;
    }

    const { code, msg } = await api(params);
    if (code == 0) {
      message.info('成功');
      setVisible(false);
      update();
    } else {
      message.error(msg);
    }
  };

  useEffect(() => {
    if (visible && league_id) {
      const { province, city, district, league_area: leagueArea } = record;
      const league_area = leagueArea ? JSON.parse(leagueArea) : [];
      const area = `${province}${city}${district}`;
      formRef.current?.setFieldsValue({ ...record, area, league_area });
    }
  }, [visible]);

  return (
    <>
      <div onClick={() => setVisible(true)}>{children}</div>
      <DrawerForm
        visible={visible}
        formRef={formRef}
        layout='horizontal'
        labelCol={{ span: 6 }}
        labelWrap
        onFinish={onFinish}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => {
            setVisible(false);
          },
        }}
        colon={false}
        submitter={{
          searchConfig: {
            resetText: '重置',
            submitText: '保存',
          },
          resetButtonProps: {
            style: league_id
              ? {
                  // 隐藏重置按钮
                  display: 'none',
                }
              : {},
          },
        }}
        width={isMobile ? '' : 700}
      >
        <ProFormText
          label='加盟商名称'
          name='league_name'
          width='sm'
          placeholder='请输入加盟商名称'
          rules={[{ required: true, message: '请输入加盟商名称' }]}
        />
        <ProFormText
          label='联系人'
          required
          width='sm'
          name='contacts_name'
          placeholder='请输入联系人'
          rules={[{ required: true, message: '请输入联系人' }]}
        />
        {!league_id && (
          <ProFormText
            label='注册手机号'
            required
            fieldProps={{
              suffix: (
                <Popover trigger={'hover'} content='注册后不可修改'>
                  <QuestionCircleOutlined />
                </Popover>
              ),
            }}
            width={'sm'}
            name='mobile'
            placeholder='请输入注册手机号'
            rules={[{ required: true, message: '请输入注册手机号' }]}
          />
        )}
        <ProFormText
          label='联系手机号'
          required
          width='sm'
          name='contacts_mobile'
          placeholder='请输入联系手机号'
          rules={[{ required: true, message: '请输入联系手机号' }]}
        />
        <ProForm.Item
          label='加盟商地址'
          name='area'
          rules={[{ required: true, message: '请输入加盟商地址' }]}
        >
          <KbAddressSelect
            level={2}
            placeholder='请输入加盟商地址'
            onChange={(_, options) => setAreaAddress(options)}
          />
        </ProForm.Item>
        <ProFormText
          name='address'
          label='详细地址'
          width='sm'
          placeholder='详细地址'
          rules={[{ required: true, message: '请输入详细地址' }]}
        />

        <ProForm.Item label='加盟区域' name='league_area'>
          <AgencyArea />
        </ProForm.Item>

        {!league_id && (
          <ProFormRadio.Group
            label='加盟商类型'
            name='league_type'
            required
            initialValue='0'
            options={[
              {
                label: '特许加盟商',
                value: 'special',
              },
              {
                label: '普通加盟商',
                value: 'normal',
              },
            ]}
          />
        )}
      </DrawerForm>
    </>
  );
};

export default AreamanageDrawer;
